import Vue from 'vue'
import { sessionStore } from 'store/dist/store.legacy'
const state = {
  url: process.env.VUE_APP_newsList_url,
  homeList: {},
  homeListPage: {},
  homeListLimit: 10,
  newsList: [],  //当前列表 list数据
  newsListPage: {},
  newsListLimit: 20
}

const mutations = {
  setNewsList (state, list) {
    state.newsList = state.newsList.concat(list)
  },
  resetNewsList (state, catId) {
    state.newsList = []
    state.catId = catId
    state.page = 1
  },
  addPage (state) {
    state.page++
  },
  setPage (state, setPage) {
    state.setPage = setPage
  },
  modifyNewsIndex (state, param) {
    state.newsIndex = param.concat()
  },
  setHomeList (state, param) {
    Vue.set(state.homeList, param.catId, param.list)
    Vue.set(state.homeListPage, param.catId, param.page)
    sessionStore.set(`homeList_${param.catId}`, param.list)
    sessionStore.set('homeListPage', state.homeListPage)
  }
}

const actions = {
  setNewsList ({ commit, state }, catId) {
    let newsListPage = sessionStore.get('newsListPage'), page
    if (!newsListPage || !newsListPage[catId]) {
      page = 1
    } else {
      page = ++newsListPage[catId]
    }
    window.axios.post(state.url, {
      cat_id: catId,
      page: page,
      limit: state.newsListLimit
    }).then(ret => {
      if (ret.data.length > 0) {
        commit()
      } else {
        return 1
      }
    })
  },
  homeListInit ({ commit, state }, catId) {
    let list = state.homeList[catId]
    if (!list || list.length == 0) {
      list = sessionStore.get(`homeList_${catId}`)
      if (list) {
        commit('setHomeList', { catId: catId, page: 1, list: list })
      } else {
        window.axios.post(state.url, {
          cat_id: catId,
          page: 1,
          limit: 10
        }).then(ret => {
          commit('setHomeList', { catId: catId, page: 1, list: ret.data })
        })
      }
    }
  },
  homeListChange ({ commit, state }, catId) {
    let homeListPage = sessionStore.get('homeListPage'), page
    if (!homeListPage || !homeListPage[catId]) {
      page = 1
    } else {
      page = ++homeListPage[catId]
    }
    window.axios.post(state.url, {
      cat_id: catId,
      page: page,
      limit: 10
    }).then(ret => {
      commit('setHomeList', { catId: catId, page: page, list: ret.data })
    })
  },
}

export default {
  state,
  mutations,
  actions
}